import { Node, instantiate } from "cc";
import { EntityTypeEnum, Singleton } from "../Common";
import { createUINode } from "../Utils";
import { EntityManager } from "../Base/EntityManager";
import ResourcesManager from "./ResourcesManager";

export class ObjectPoolManager extends Singleton {

    static get Ins() {
        return super.GetInstance<ObjectPoolManager>()
    }

    private entityPool: Map<EntityTypeEnum, Node[]> = new Map()

    /** 对象池子分配对象 */
    poolAlloc(type: EntityTypeEnum): Node {
        const pool = this.entityPool.get(type)
        if (pool && pool.length) {

            const node = pool.pop()
            node.active = true
            return node
        } else {
            const prefab = ResourcesManager.Ins.prefabMap.get(type)
            return prefab ? instantiate(prefab) : createUINode(type)
        }
    }

    /** 对象池添加对象 */
    poolFree(em: EntityManager) {
        const pool = this.entityPool.get(em.type)
        if (!pool) {
            this.entityPool.set(em.type, [em.node])
        } else {
            pool.push(em.node)
        }
        em.node.active = false
    }

    /** 对象池添加对象 */
    poolFreeNode(type: EntityTypeEnum, node: Node) {
        const pool = this.entityPool.get(type)
        if (!pool) {
            this.entityPool.set(type, [node])
        } else {
            pool.push(node)
        }
        node.active = false
    }

    reset() {
        this.entityPool = new Map()
    }
}